03. The Dot Operator

When learning about objects like the robot in the Maze app, we used the dot operator to get access to the robot’s actions.

The dot operator reveals the robot's actions.

The dot operator reveals the robot's actions.

Similarly, when working with structs, we use the dot operator to get access to the struct’s properties. Here is all our code again for the Student, Point2D, and GeoLocation structs. We also have an instance of each struct. The instance names are ayush, characterPosition, and udacityCoordinates.

struct Student {
    let name: String
    var age: Int
    var school: String
}

struct Point2D {
    var x: Int = 0
    var y: Int = 0
}

struct GeoLocation {
    var latitude: Double = 0.0
    var longitude: Double = 0.0
}

var ayush = Student(name: "Ayush Saraswat", age: 19, school: "Udacity")
var characterPosition = Point2D(x: 10, y: 10)
let udacityCoordinates = GeoLocation(latitude: 37.400073, longitude: -122.108400)

To access their properties, we use the following syntax:

The syntax for accessing a property is an instance name followed by the property name.

The syntax for accessing a property is an instance name followed by the property name.

By using this syntax, we can retrieve or change property values for instances of structs.

Changing Struct Properties

For example, ayush is now a year older and studying at USC. So we should update his properties.

The eye icon gives us a "Quick Look" at a struct's properties.

The eye icon gives us a "Quick Look" at a struct's properties.

With the dot operator, these are quick changes. And, by clicking the eye icon in the right pane, you can see that the property values have updated correctly.

We cannot, however, change his name, because if we look back at the definition for the Student struct, name is declared as a constant.

The name property cannot be changed because it is a constant.

The name property cannot be changed because it is a constant.

Can We Change Other Properties?

QUESTION:

Can we change the property values of udacityCoordinates?

struct GeoLocation {
    var latitude: Double = 0.0
    var longitude: Double = 0.0
}

let udacityCoordinates = GeoLocation(latitude: 37.400073, longitude: -122.108400)
ANSWER:

The answer is also no because udacityCoordinates—although an instance of the GeoLocation struct—has been declared as a constant.This means despite the fact that the individual properties are variables, this particular instance is constant and cannot change.

If you try this yourself in a Playground file, you'll see Swift compiler complains, but it also recommends we change let to var so that we can update the property value. If we do this, the compiler no longer complains and the statement executes normally.